package com.tql.mall.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tql.mall.model.enums.OrderStatus;
import com.tql.mall.model.enums.PaymentType;
import com.tql.mall.model.order.OrderInfo;
import com.tql.mall.model.payment.PaymentInfo;
import com.tql.mall.order.client.OrderFeignClient;
import com.tql.mall.payment.mapper.PaymentInfoMapper;
import com.tql.mall.payment.service.PaymentService;
import com.tql.mall.rabbit.constant.MqConstant;
import com.tql.mall.rabbit.service.RabbitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: tyk
 * @Date: 2023/5/27 17:10
 * @Description:
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private RabbitService rabbitService;

@Override
public Boolean doPay(Long orderId) {
    // 查询订单
    OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
    // 判断
    if (orderInfo == null || !OrderStatus.UNPAID.name().equals(orderInfo.getOrderStatus())) return false;

    // 保存支付信息
    savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());

    // TODO 对接第三方支付

    // 修改订单状态并拆单
    rabbitService.sendMsg(MqConstant.EXCHANGE_PAY, MqConstant.ROUTING_PAY, orderId);

    return true;
}

    @Override
    public void savePaymentInfo(OrderInfo orderInfo, String paymentType) {

        // 判断支付记录信息是否存在
        LambdaQueryWrapper<PaymentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaymentInfo::getOrderId, orderInfo.getId());
        wrapper.eq(PaymentInfo::getPaymentType, paymentType);
        Integer count = paymentInfoMapper.selectCount(wrapper);
        if (count > 0) return;

        // 保存支付记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setUserId(orderInfo.getUserId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
        paymentInfo.setSubject(orderInfo.getTradeBody());
        paymentInfoMapper.insert(paymentInfo);
    }

}
